import logging
from . import index_blue
from flask import render_template, current_app, request, jsonify, g
from info import models, constants
from info.utils.response_code import *
from info.utils.common import check_islogin





@index_blue.route("/favicon.ico")
def setFavicon():
    return current_app.send_static_file("news/favicon.ico")

# 返回模板
@index_blue.route("/")
@check_islogin
def index():
    # logging.debug("This is a debug log.")
    # logging.info("This is a info log.")
    # logging.warning("This is a warning log.")
    # logging.error("This is a error log.")
    # logging.critical("This is a critical log.")
    # 发送到前段的数据
    data={
        # 用于模板判断是否显示登陆
        # "isLogin":False,
        "user_info":None,
        "click_news_list":None,
        "category_list":None,
    }
    # 判断是的登录
    user = g.user
    if user:
        # data["isLogin"] = True
        data["user_info"] = user.to_dict() if user else None

    # # 获取session中的值
    # user_id = session.get("user_id")
    # # 判断是否登录
    # if user_id:
    #     data["isLogin"] = True
    #     user = models.User.query.get(user_id)
    #     print(user.nick_name)
    #     #　加入用户信息
    #     data["user_info"] = user


    # 获取点击排行榜的数据
    news = models.News.query.order_by(models.News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    news_list = [x.to_dict() for x in news ]
    data["click_news_list"] = news_list
    # 获取分类信息
    category = models.Category.query.all()
    category_list = [x.to_dict() for x in category]
    data["category_list"] = category_list
    return render_template("news/index.html", data = data)



# 新闻列表数据
@index_blue.route("/news_list")
def fancNewList():
    # 　获取浏览器数据
    cid = request.args.get("cid", "1")
    page = request.args.get("page", "1")
    per_page = request.args.get("per_page", "10")

    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        cid = 1
        page = 1
        per_page = 10
    print(cid)
    # if cid == 1:
    #     paginate = models.News.query.order_by(models.News.create_time.desc()).paginate(page, per_page, False)
    # else:
    #     paginate = models.News.query.filter(models.News.category_id == cid).order_by(models.News.create_time.desc()).paginate(page, per_page, False)
    #　设置过滤器参数
    my_filter = [ ]
    if cid != 1:
        my_filter.append(models.News.category_id == cid)

    # 　获取分页信息
    paginate = models.News.query.filter(*my_filter).order_by(models.News.create_time.desc()).paginate(page, per_page, False)
    # 当前页
    currentPage = paginate.page
    # 总页数
    pages = paginate.pages
    # 查询出来的总信息
    datas = paginate.items
    # 记录总条数
    # newsTotal = paginate.total
    data_list = [data.to_dict() for data in datas]
    data = {
        "news_dict_li":data_list,
        "current_page":currentPage,
        "total_page": pages
    }
    return jsonify(errno=RET.OK, errmsg="ok", data = data)




